//
//  Tzbzsh.swift
//  Auscultation
//
//  Created by 来 on 2020/12/9.
//

import UIKit

class TzbzshVC: BaseVC {
    
    var type: String = ""
    
    var status: Int = 10
    
    var id: String = ""
    
    var navi_title: String = ""
    
    var collectionView: UICollectionView!
    
    var dataArray: [[String: Any]] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadData))
        NotificationCenter.default.addObserver(self, selector: #selector(TzbzshVC.loadData), name: NSNotification.Name(rawValue: "ReloadTzbzshVC"), object: nil)
        loadData()
    }
    
    // 数据刷新
    @objc func loadData() {
        dataArray.removeAll()
        loadMoreData()
    }
    @objc func loadMoreData() {
        let paramet: [String: String] = [
            "userId": EWEUser.lgf.userId ?? "",
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf(type == "标注" ? ("label/" + id) : ("audit/" + id), paramet, .get) { [weak self] (data) in
            let result = (data["sample"] as? [[String: Any]]) ?? []
            if result.count > 0 {
                self?.dataArray += result
            }
            self?.collectionView.reloadData()
            self?.endRefreshing()
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    func endRefreshing() {
        self.collectionView.mj_header?.endRefreshing()
    }
    
    @objc func wancheng(_ sender: UIButton) {
        if sender.titleLabel?.text == "返回" {
            self.navigationController?.popViewController(animated: true)
            return
        }
        if self.type == "标注" {
            var wwc = false
            dataArray.forEach { (dict) in
                let status = (dict["labelStatus"] as? Int) ?? 0
                if status != 20 {
                    wwc = true
                    return
                }
            }
            if wwc {
                SVProgressHUD.showError("有标注包未完成")
                return
            }
            let paramet: [String: Any] = [
                "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
            ]
            EWERequest.lgf("label/" + self.id + "?userId=" + (EWEUser.lgf.userId ?? ""), paramet, .put, JSONEncoding.default) { [weak self] (data) in
                SVProgressHUD.showSuccess("标注完成")
                Timer.lgf_After(S: 0.5) {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadBzgztVC"), object: nil)
                    self?.navigationController?.popViewController(animated: true)
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        } else {
            var wwc = false
            dataArray.forEach { (dict) in
                let status = (dict["labelStatus"] as? Int) ?? 0
                if status != 20 {
                    wwc = true
                    return
                }
            }
            if wwc {
                SVProgressHUD.showError("有审核包未完成")
                return
            }
            let paramet: [String: Any] = [
                "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
            ]
            EWERequest.lgf("audit/" + self.id, paramet, .put, JSONEncoding.default) { [weak self] (data) in
                SVProgressHUD.showSuccess("审核完成")
                Timer.lgf_After(S: 0.5) {
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadShgztVC"), object: nil)
                    self?.navigationController?.popViewController(animated: true)
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        }
    }
    
}

extension TzbzshVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 95)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: TzbzshCell.self, for: indexPath)
        if type == "标注" {
            cell.tzzx.text = (dataArray[indexPath.item]["no"] as? String) ?? ""
            let status = (dataArray[indexPath.item]["labelStatus"] as? Int) ?? 0
            // 标注状态：0：未开始；10：标注开始；20：标注完成
            if status == 0 {
                cell.button.text = "标注"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")
            } else if status == 10 {
                cell.button.text = "标注"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "0F88F2")
            } else if status == 20 {
                cell.button.text = "查看"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")
            }
        } else {
            let status = (dataArray[indexPath.item]["auditStatus"] as? Int) ?? 0
            // 审核状态：0：未开始；10：审核开始；20：审核完成
            if status == 0 {
                cell.button.text = "审核"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")
            } else if status == 10 {
                cell.button.text = "审核"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "0F88F2")
            } else if status == 20 {
                cell.button.text = "查看"
                cell.button.backgroundColor = UIColor.init(lgf_HexString: "F27C0F")
            }
            cell.tzzx.text = (dataArray[indexPath.item]["labelName"] as? String) ?? ""
        }
        cell.tw.text = "体位：" + ((dataArray[indexPath.item]["position"] as? String) ?? "")
        cell.phcd.text = "配合程度：" + ((dataArray[indexPath.item]["coordinate"] as? String) ?? "")
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let vc = BzVC()
        if type == "标注" {
            let status = (dataArray[indexPath.item]["labelStatus"] as? Int) ?? 0
            // 标注状态：0：未开始；10：标注开始；20：标注完成
            if status == 20 {
                vc.type = 1
            } else {
                vc.type = 2
            }
            vc.stype = 1
            vc.labelStatus = status
        } else {
            let status = (dataArray[indexPath.item]["auditStatus"] as? Int) ?? 0
            // 审核状态：0：未开始；10：审核开始；20：审核完成
            if status == 20 {
                vc.type = 3
            } else {
                vc.type = 4
            }
            vc.stype = 2
            vc.auditStatus = status
        }
        vc.id = (dataArray[indexPath.item]["id"] as? String) ?? ""
        self.navigationController?.show(vc, sender: self)
    }
}
